package com.tql.pandian.service.impl;

import com.ruoyi.common.core.utils.CalculatedValueUtil;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.TimeUtils;
import com.ruoyi.common.datasource.annotation.Master;
import com.ruoyi.common.datasource.annotation.Slave;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.tql.pandian.entity.TqlStapInChangeEntity;
import com.tql.pandian.entity.analysis.TqlCaseAnlasysEntity;
import com.tql.pandian.entity.analysis.dto.BillFoodReportDayDto;
import com.tql.pandian.entity.analysis.dto.SaleDataDTO;
import com.tql.pandian.entity.analysis.vo.*;
import com.tql.pandian.entity.dto.StageOperationDTO;
import com.tql.pandian.entity.dto.StockDTO;
import com.tql.pandian.entity.dto.TargetManageDTO;
import com.tql.pandian.entity.vo.CaseAnalsysDto;
import com.tql.pandian.mapper.CostAnalysisMapper;
import com.tql.pandian.service.IAnotherDataBaseService;
import com.tql.pandian.service.ICostAnalysisService;
import com.tql.pandian.util.CommonUtilHll;
import com.ruoyi.common.core.constant.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import  com.tql.pandian.entity.analysis.vo.StapProlossByArrVo;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CostAnalysisService implements ICostAnalysisService {

    @Autowired
    private CostAnalysisMapper costAnalysisMapper;

    @Autowired
    private IAnotherDataBaseService anotherDataBaseService;

    @Override
    public List<BillFoodReportDayDto> getSaleData(Map<String, Object> params) {
        String date = (String) params.get("date");
        String deptId = (String) params.get("deptId");
        Calendar now = Calendar.getInstance();
        int month = now.get(Calendar.MONTH) + 1;
        Date date1=null;
        if (StringUtils.isNotBlank(date)) {
            try {
                // 创建SimpleDateFormat对象，用于解析日期字符串
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                 date1=sdf.parse(date);

                // 获取日期对象中的日部分
                month =date1.getMonth() +1;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        String tablename = CommonUtil.TABLE_BILL_FOOD_REPORT + month;
        Long data1=TimeUtils.getStringDateToLong(date1);
        List<BillFoodReportDayDto> foodReportVoList = anotherDataBaseService.getFoodReportVoList(data1, tablename,deptId);
        if (!CollectionUtils.isEmpty(foodReportVoList)) {
            List<String> foodCodes = foodReportVoList.stream().map(BillFoodReportDayDto::getFoodCode).collect(Collectors.toList());
            List<BillFoodReportDayDto> list1 = anotherDataBaseService.findDishFood(foodCodes, deptId);
            Map<String, String> map = list1.stream()
                    .collect(Collectors.toMap(BillFoodReportDayDto::getFoodCode, BillFoodReportDayDto::getDeptName));
            foodReportVoList.stream().forEach(e -> {
                String foodCode = e.getFoodCode();
                String deptName = map.get(foodCode);
                int hasBom = Optional.ofNullable(deptName)
                        .filter(name -> !name.isEmpty())
                        .map(name -> 1)
                        .orElse(0);
                e.setDeptName(deptName);
                e.setHasBom(hasBom);

            });
        }
////            List<SaleDataArrVo> saleDataArrVoList = costAnalysisMapper.selectSaleDataArrVo(foodCodes, Long.valueOf(deptId));
//            return foodReportVoList.stream().peek(m->{
//                if (!CollectionUtils.isEmpty(saleDataArrVoList)){
//                    saleDataArrVoList.forEach(t->{
//                        if (t.getFoodCode().equals(m.getFoodCode())){
//                            m.setSaleDataArrVo(t);
//                        }
//                    });
//                }
//            }).collect(Collectors.toList());
//        }
        return foodReportVoList;
        /*return costAnalysisMapper.selectSaleData(map);*/
    }

    @Slave
    @Override
    public List<TqlCaseAnlasysEntity> getStock(StockDTO dto) throws ParseException {
        int month = CommonUtilHll.getCurrentMonth(new Date());
        if (!dto.getParamTime().isEmpty()) {
            month = TimeUtils.getMonth(dto.getParamTime(), "yyyy-MM-dd");
        }
        return costAnalysisMapper.selectInventory(dto,CommonUtil.TABLE_CASE_ANLASYS+month);
    }




    /**
     * 折前标准毛利率
     * @param dto
     * @return
     */
    @Override
    public List<TargetManageVo> getTargetManageDiscount(TargetManageDTO dto) {
        //默认当月时间
        if (StringUtils.isEmpty(dto.getParamDate())){
            dto.setParamDate(CommonUtilHll.getMonthDate(new Date()));
        }else if (StringUtils.isNotEmpty(dto.getStartTime()) || StringUtils.isNotEmpty(dto.getEndTime())){
            dto.setParamDate(null);
        }
        if (StringUtils.isEmpty(dto.getParamMounth())){
            dto.setParamMounth(String.valueOf(CommonUtilHll.getCurrentMonth(new Date())));
        }
        Map paramMap = new HashMap();
        paramMap.put("tableName",CommonUtil.TABLE_SHOP_BILL+dto.getParamMounth());
        paramMap.put("paramDate",dto.getParamDate());
        paramMap.put("deptCode",dto.getDeptCode());
        List<ShopBillListVo> list = anotherDataBaseService.getShopBillListVo(paramMap);

        if (!CollectionUtils.isEmpty(list)){
            Long[] shaopIdS=list.stream().map(ShopBillListVo::getShopId).toArray( Long[]::new);
            List<StapProlossByArrVo> ArrVoS =costAnalysisMapper.selectStapProlossByArr(shaopIdS);
            list.stream().map(t->{
                ArrVoS.forEach(k->{
                    if (k.getShopCode().equals(t.getShopId())){
                        t.setInAmout(k.getInAmout());
                    }
                });
                return t;
            }).collect(Collectors.toList());
            //计算
            return list.stream().map(k->{
                TargetManageVo vo = new TargetManageVo();
                vo.setCreateDate( k.getCreateDate());
                BigDecimal foodAmount = k.getFoodAmount();
                BigDecimal inAmout;
                if (k.getInAmout() == null){
                    inAmout = new BigDecimal(0);
                }else {
                    inAmout = k.getInAmout();
                }
                if (foodAmount.compareTo(BigDecimal.ZERO) != 0){
                    BigDecimal profit = CalculatedValueUtil.subtractionBigDecimal(foodAmount, inAmout);
                    BigDecimal rate = CalculatedValueUtil.division(profit,foodAmount);
                    BigDecimal divide = CalculatedValueUtil.subtractionBigDecimal(foodAmount,inAmout);
                    vo.setRate(rate);
                    vo.setDivide(divide);
                }else {
                    vo.setRate(new BigDecimal(0));
                    vo.setDivide(new BigDecimal(0));
                }
                return vo;
            }).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 实际毛利率
     * @param dto
     * @return
     */
    @Override
    public List<TargetManageVo> getTargetManageReal(TargetManageDTO dto) {
        if (StringUtils.isEmpty(dto.getParamDate())){
            dto.setParamDate(CommonUtilHll.getMonthDate(new Date()));
        }
        if (StringUtils.isEmpty(dto.getParamMounth())){
            dto.setParamMounth(String.valueOf(CommonUtilHll.getCurrentMonth(new Date())));
        }
        Map paramMap = new HashMap();
        paramMap.put("tableName",CommonUtil.TABLE_OUT_CHANGE+dto.getParamMounth());
        paramMap.put("paramTime",dto.getParamDate());
        List<RealSummaryVo> realSummaryVoList = anotherDataBaseService.getRealSummary(dto.getParamDate(),
                CommonUtil.TABLE_OUT_CHANGE+dto.getParamMounth());
        if (!CollectionUtils.isEmpty(realSummaryVoList)){
            List<String> foodCodes = realSummaryVoList.stream().map(RealSummaryVo::getFoodCode).collect(Collectors.toList());
            List<DishBomRealVo> dishBomRealVoList = costAnalysisMapper.selectDishBomReal(foodCodes);
            return realSummaryVoList.stream().map(k->{
                TargetManageVo vo = new TargetManageVo();
                vo.setCreateDate( k.getCreateTime());
                BigDecimal sumcost;
                if (k.getSumcost() == null){
                    sumcost = new BigDecimal(0);
                }else {
                    sumcost = k.getSumcost();
                }
                if (!CollectionUtils.isEmpty(dishBomRealVoList)){
                    dishBomRealVoList.forEach(m->{
                        if (k.getFoodCode().equals(m.getFoodCode())){
                            BigDecimal cost;
                            if (m.getCost() == null){
                                cost = new BigDecimal(0);
                            }else {
                                cost = m.getCost();
                            }
                            //BigDecimal rate = cost.divide(sumcost).setScale(4,BigDecimal.ROUND_UP).multiply(new BigDecimal(100));

                            BigDecimal profit = CalculatedValueUtil.division(cost,sumcost);
                            BigDecimal mul = CalculatedValueUtil.multiplyB(profit,new BigDecimal(100));
                            BigDecimal dValue = CalculatedValueUtil.subtractionBigDecimal(mul,new BigDecimal(69));
                            vo.setRate(mul);
                            vo.setDivide(dValue);
                            /*h.put("rate",rate);
                            h.put("dValue",rate.divide(new BigDecimal(69)));*/
                        }
                    });
                }else {
                    vo.setRate(new BigDecimal(0));
                    vo.setDivide(new BigDecimal(0));
                }
                return vo;
            }).collect(Collectors.toList());
        }
        return null;
    }

    @Slave
    @Override
    public List<OperationVo> getStageOperation(StageOperationDTO dto) {
        Map map = new HashMap();

        map.put("shopCode",dto.getShopCode());
        if (StringUtils.isEmpty(dto.getParamTime())){
            map.put("paramTime",CommonUtilHll.getMonthDate(new Date()));
        }else {
            map.put("paramTime",dto.getParamTime());
        }
        if (dto.getMouthDay() == null){
            map.put("shopBill",CommonUtil.TABLE_SHOP_BILL+CommonUtilHll.getCurrentMonth(new Date()));
            map.put("stapOutChange",CommonUtil.TABLE_OUT_CHANGE+CommonUtilHll.getCurrentMonth(new Date()));
            map.put("stapInChange",CommonUtil.TABLE_IN_CHANGE+CommonUtilHll.getCurrentMonth(new Date()));
        }else {
            map.put("shopBill",CommonUtil.TABLE_SHOP_BILL+dto.getMouthDay());
            map.put("stapOutChange",CommonUtil.TABLE_OUT_CHANGE+dto.getMouthDay());
            map.put("stapInChange",CommonUtil.TABLE_IN_CHANGE+dto.getMouthDay());
        }

        /*map.put("shopBill","tql_hll_shop_bill"+dto.getMouthDay());
        map.put("stapOutChange","tql_stap_out_change"+dto.getMouthDay());
        map.put("stapInChange","tql_stap_in_change"+dto.getMouthDay());*/
        //List<Map> list = costAnalysisMapper.selectStageOperation(map);
        return costAnalysisMapper.selectStageOperation(map).stream().map(t->{
            OperationVo vo = new OperationVo();
            Map m = new HashMap();
            vo.setCreateDate(t.getCreateDate());
            if (t.getFoodAmount() == null){
                vo.setFoodAmount(new BigDecimal(0));
                vo.setDiscount(new BigDecimal(0)); //折前标准毛利率
                vo.setGross(new BigDecimal(0));  //毛利率
            }else {
                vo.setFoodAmount(t.getFoodAmount());
                if ( t.getSumcost() != null || t.getFoodAmount().compareTo(BigDecimal.ZERO) != 0){
                    BigDecimal discount = CalculatedValueUtil.division(t.getSumcost(),t.getFoodAmount());
                    m.put("discount",discount);
                }
                if (t.getFAllAmount() != null){
                    BigDecimal gross = CalculatedValueUtil.subtractionBigDecimal(t.getFoodAmount(),t.getFAllAmount());
                    m.put("gross",gross);
                }
            }
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public StageOperationDTO getStageOperation1(StageOperationDTO dto) {
        String pandianCode=dto.getPandianCode();
        StageOperationDTO dto1=costAnalysisMapper.getStageOperation1(pandianCode);
        if(null!=dto1)
        {
            BigDecimal sellAmount=null==dto1.getSumAmount()?BigDecimal.ZERO:dto1.getSumAmount();
            BigDecimal sumRealCost=null==dto1.getSumRealCost()?BigDecimal.ZERO:dto1.getSumRealCost();
            BigDecimal sumStandardCost=null==dto1.getSumStandardCost()?BigDecimal.ZERO:dto1.getSumStandardCost();
            BigDecimal standardProMargin=null;
            if(!sellAmount.equals(BigDecimal.ZERO)&&!sumStandardCost.equals(BigDecimal.ZERO))
            {
                standardProMargin=CalculatedValueUtil.division(sumStandardCost,sellAmount);
                dto1.setStandardProMargin(standardProMargin);
                BigDecimal dd=CalculatedValueUtil.multiplication(standardProMargin,100);
                dto1.setStandardProMarginStr(dd.toPlainString()+"%");

            }

            BigDecimal realCostMargin=null;
            if(!sellAmount.equals(BigDecimal.ZERO)&&!sumRealCost.equals(BigDecimal.ZERO))
            {
                realCostMargin=CalculatedValueUtil.division(sumRealCost,sellAmount);
                dto1.setRealCostMargin(realCostMargin);
                BigDecimal dd=CalculatedValueUtil.multiplication(realCostMargin,100);
                dto1.setRealCostMarginStr(dd.toPlainString()+"%");
            }


        }
        return dto1;
    }

    @Override
    @Master
    public List<TqlCaseAnlasysEntity> findStapNameAndDeptName(List<TqlCaseAnlasysEntity> list,int flag) {
        if(1==flag)
       return  costAnalysisMapper.findStapNameAndDeptName(list);
        if(2==flag)
            return  costAnalysisMapper.findStapNameAndDeptName1(list);
        return null;
    }

    @Override
    @Slave
    public List<TqlStapInChangeEntity>  getCaseAnalsysIninfo(String inids, int month) {

            String tableNaum=CommonUtil.TABLE_IN_CHANGE+month;
        Long[] longArray = Arrays.stream(inids.split(","))
                .map(Long::parseLong)
                .toArray(Long[]::new);
            return  costAnalysisMapper.getCaseAnalsysIninfo(longArray,tableNaum);


    }


}
